package com.ruoyi.util;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/api")
public class ImageController {

    static Logger log = LoggerFactory.getLogger(ImageController.class);

    @Value("${ruoyi.profile}")
    private String uploadDir; // 从 application.yml 读取上传路径
    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

    public static String getDomain(HttpServletRequest request) {
        StringBuffer url = request.getRequestURL();
        String contextPath = request.getServletContext().getContextPath();
        return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString();
    }

    @ApiOperation("上传图片")
    @PostMapping("/upload")
    public R<String> uploadImage(
            @RequestParam("file") MultipartFile file,
            HttpServletRequest request
    ) {
        try {
            // 若依权限校验（示例）
            //LoginUser loginUser = (LoginUser) SecurityUtils.getLoginUser();

            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());

            // 广播消息到所有订阅客户端
            simpMessagingTemplate.convertAndSend("/topic/images", url);

            return R.ok(url);
        } catch (Exception e) {
            log.error("上传失败", e);
            return R.fail("上传失败：" + e.getMessage());
        }
    }

    public String getUrl() {
        HttpServletRequest request = ServletUtils.getRequest();
        return getDomain(request);
    }
}
